package com.binvshe.binvshe.mine.corporation.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.utils.FragmentUtils;
import com.binvshe.binvshe.app.MainActivity;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.ListDataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 */
public class TansferFragment extends SwipeListFragment {

    private int mPage = 0;

    public static TansferFragment newInstance() {
        Bundle args = new Bundle();
        TansferFragment fragment = new TansferFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        mPage = 0;
        startLoading();
    }

    public TansferFragment() {
    }


    private ListDataRequestListener<Account> mResponceListener = new ListDataRequestListener<>(this, Account.class, true);

    void getMemberData() {
        if (mResponceListener.getResponseDataParser().hasMore()) {
            mPage++;
        }
        MyHttpRequest request = new MyHttpRequest(getActivity());
        String url = String.format(UrlCenter.CLUB_MEMBER, AccountManager.getCurrentAccount().getClub().getId());
        Log.e("getMemberData: ", url);
        UrlParams urlParams = new UrlParams();
        urlParams.put(ParamKey.PAGE, mPage + "");
        urlParams.put(ParamKey.SIZE, 8 + "");
        request.get(url, urlParams, mResponceListener);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        initToolBar();
        startLoading();
        return view;
    }

    private void initToolBar() {
        showToolbar();
        setTitle("社团转让");
        ImageButton backButton = getCustomToolbar().enableBackButton();
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentUtils.backStack(getActivity());
            }
        });
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new ClubMemberAdapter(getActivity());
    }

    @Override
    public void onStartLoading() {
        getMemberData();
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        startLoading();
    }

    private void transferClub(int clubId, String userId) {
        MyHttpRequest request = new MyHttpRequest(getActivity());
        String url = String.format(UrlCenter.TRANSFER_CLUB, clubId, userId);
        request.put(url, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String str) {
                super.onSuccess(str);
                EasyToast.showToast(getContext(), "转让成功!");
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(getContext(), strMsg);
            }
        });
    }


    public class ClubMemberAdapter extends RecyclerViewBaseAdapter<Account> {


        public ClubMemberAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_club_member));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final Account member = getData().get(position);
            if (!TextUtils.isEmpty(member.getNickName()))
                viewHolder.mTvName.setText(member.getNickName());
            if (!TextUtils.isEmpty(member.getPortrait()))
                IML.load(getActivity(), viewHolder.mCirHead, member.getPortrait());
            if (!TextUtils.isEmpty(member.getCity()))
                viewHolder.mTvCity.setText(member.getCity());

            setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                    final AlertDialogFragment alertDialog = new AlertDialogFragment();
                    alertDialog.setMessage("是否将社团转让给" + getData().get(position).getNickName() + "?")
                            .setNegativeButton("不要", true, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialog.dismiss();
                                }
                            })
                            .setPositiveButton("可以", false, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    transferClub(getData().get(position).getClub().getId(), getData().get(position).getUserId());
                                    alertDialog.dismiss();
                                    startActivity(new Intent(getActivity(), MainActivity.class));
                                }
                            })
                            .show(getFragmentManager());
                }
            });
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.mCirHead)
            CircleImageView mCirHead;
            @Bind(R.id.mTvName)
            TextView mTvName;
            @Bind(R.id.mTvCity)
            TextView mTvCity;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
